<template>
  <div class="app-container">
    <div class="content-container">
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item prop="commissionStatus" label="状态">
            <el-select
              v-model="queryParams.commissionStatus"
              placeholder="请选择状态"
              class="!w-[240px]"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="ownName" label="业主姓名">
            <el-input v-model="queryParams.ownName" placeholder="请输入业主姓名" clearable />
          </el-form-item>
          <el-form-item prop="keywords" label="签约时间">
            <el-date-picker
              v-model="startEndTime"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleChangeDate"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="search" @click="handleSearch">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="activeName" class="enter-tabs" @tab-change="handleClick">
        <el-tab-pane label="设计师-装修公司佣金" name="designer"></el-tab-pane>
        <el-tab-pane label="建材商佣金" name="company"></el-tab-pane>
      </el-tabs>
      <el-card shadow="never" class="table-card">
        <div class="table-card-body">
          <BasePageTable
            :table-data="tableData"
            :table-columns-data="tableColumnsData"
            :total="total"
            :loading="loading"
            @handleQuery="changePage"
          >
            <template #region="{ row, name }">
              {{ `${row.commissionExt?.region}${row.commissionExt?.houseNumber}` }}
            </template>
            <template #commission="{ row, name }">
              {{ row.commission || 0 }}
            </template>
            <template #contractAmount="{ row, name }">
              {{ row.contractAmount || 0 }}
            </template>
            <template #commissionStatus="{ row, name }">
              <el-tag :type="COMMISSION_STATUS_MAP[row.commissionStatus] || 'info'">
                {{ getLabelByValue(COMMISSION_STATUS_ENUM, row.commissionStatus) }}
              </el-tag>
            </template>
            <template #isOverdue="{ row, name }">
              <el-tag :type="IS_OVERDUE_MAP[row.isOverdue] || 'info'">
                {{ getLabelByValue(IS_OVERDUE_ENUM, row.isOverdue) }}
              </el-tag>
            </template>
            <template #contractFile="{ row, name }">
              <image-preview
                v-for="(item, index) in JSON.parse(row.contractFile || '[]')"
                :key="index"
                width="100px"
                height="100px"
                class="mr-xs"
                :src="item.url"
              ></image-preview>
            </template>
            <template #operation="{ row, name }">
              <el-button link type="primary" icon="Edit" @click="handleViewDetail(row)">
                查看详情
              </el-button>
              <el-button link type="primary" icon="Edit" @click="handleFree(row)">免佣金</el-button>
            </template>
          </BasePageTable>
        </div>
      </el-card>
    </div>
    <commission-form ref="commissionFormRef"></commission-form>
    <el-dialog
      v-model="freeDiv"
      title="确定不收取该商户的成交佣金吗?"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules">
        <el-form-item label="免佣图片" prop="commissionFreeVoucher">
          <MultiImageUpload v-model="formData.commissionFreeVoucher" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit" v-loading="loading">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import BasePageTable from "@/components/BasePageTable/index.vue";
import { getLabelByValue, getLabelValueList } from "@/utils/enums";
import { CONTACT_TYPE, UserTypeEnum } from "../../../enums/system/UserEnum";
import CommissionForm from "@/views/commission/commissionList/components/commission-form.vue";
import commissionAPI, { ConsumerHouseDesignLinkVO } from "@/api/commission/index";
import { useUserStore } from "@/store";
import {
  COMMISSION_STATUS_ENUM,
  COMMISSION_STATUS_MAP,
  IS_OVERDUE_ENUM,
  IS_OVERDUE_MAP,
} from "@/enums/commission/commissionEnum";
import ImagePreview from "@/components/ImagePreview/index.vue";
import { ref } from "vue";
const { userInfo } = useUserStore();
const loading = ref(false);
const commissionFormRef = ref();
const total = ref(0);
const queryFormRef = ref();
const startEndTime = ref();
const activeName = ref("designer");
import { dayjs } from "element-plus";
import { companyColumn, designerColumn } from "@/views/commission/commissionList/index";
const options = getLabelValueList(COMMISSION_STATUS_ENUM);
const queryParams = reactive({
  commissionStatus: "",
  ownName: "",
  contractBeginTime: "",
  contractEndTime: "",
  pageNum: 1,
  pageSize: 10,
});
const tableData = ref<ConsumerHouseDesignLinkVO[]>([]);
const tableColumnsData = computed(() =>
  activeName.value === "designer" ? designerColumn : companyColumn
);

const formRef = ref();
const freeDiv = ref(false);
const formData = ref({
  id: null,
  commissionFreeVoucher: [],
});
const formRules = reactive({
  commissionFreeVoucher: [{ required: true, message: "请上传凭证", trigger: "change" }],
});
const contractFileLoading = ref(false);

async function getPage(params) {
  if (activeName.value === "designer") {
    return await commissionAPI.getDesignPage(params);
  } else {
    return await commissionAPI.getMaterialBuyPage(params);
  }
}
// 查询
function handleQuery() {
  loading.value = true;
  getPage(queryParams)
    .then((data) => {
      tableData.value = data.list || [];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
function handleSearch() {
  queryParams.pageNum = 1;
  handleQuery();
}

function changePage(val: any) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  handleQuery();
}
// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  startEndTime.value = "";
  queryParams.contractBeginTime = "";
  queryParams.contractEndTime = "";
  handleQuery();
}
function handleCloseDialog() {
  freeDiv.value = false;
}
function handleFree(val: any) {
  formData.value.id = val.id;
  freeDiv.value = true;
}
async function handleSubmit() {
  loading.value = true;
  const commissionFreeFrom = {
    id: formData.value.id,
    commissionFreeVoucher: JSON.stringify(formData.value.commissionFreeVoucher),
  };
  await commissionAPI
    .commissionFree(commissionFreeFrom)
    .then((res) => {
      console.log(res);
      freeDiv.value = false;
      handleQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}
async function handleViewDetail(val) {
  commissionFormRef.value.showModal(val);
}

async function handleClick(val) {
  handleSearch();
}

async function handleChangeDate(val) {
  const [startTime, endTime] = val;
  queryParams.contractBeginTime = startTime;
  queryParams.contractEndTime = dayjs(endTime).format("YYYY-MM-DD 23:59:59");
}

onMounted(async () => {
  handleQuery();
});
</script>
